import React, {
  useRef,
  useContext,
  useState,
  useCallback,
  useEffect,
} from "react";
import {
  ProColumns,
  ProTable,
  ActionType,
  TableDropdown,
} from "@ant-design/pro-components";
import { Space, Tag, Tooltip, Switch, Select, Button, Modal } from "antd";
import { WifiOutlined, DisconnectOutlined } from "@ant-design/icons";
import { http_request, ac_cgi_url } from "@src/Common/Request";
import { AllContext } from "@src/Common/AllContext";
import useInterval from "@src/Common/useInterval";
import { getColumnSearchProps } from "@src/Common/TableSearch";
import "../index.css";
import {
  DeviceListItem,
  refreshOptions,
  buttonStyle,
  getColumns,
} from "./data";

const DevListView: React.FC<{ groupId: string }> = ({ groupId }) => {
  const { devType, messageApi } = useContext(AllContext);
  const actionRef = useRef<ActionType>();
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [refreshInterval, setRefreshInterval] = useState<number>(3); // 默认3秒
  const [deviceListData, setDeviceListData] = useState<DeviceListItem[]>([]);
  const [loading, setLoading] = useState(false);
  // 新增状态用于控制展开的行
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  // 新增状态用于批量操作所选择的行
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  // 添加对devType的监听，确保切换设备类型时重新加载数据
  useEffect(() => {
    // 清空之前的数据
    setDeviceListData([]);
    // 重置选中状态
    setSelectedRowKeys([]);
    // 重置展开状态
    setExpandedRowKeys([]);
    // 主动请求新数据
    fetchDeviceList();
    // 通知表格组件刷新
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }, [devType]); // 只监听devType变化

  // 获取设备列表数据的函数
  const fetchDeviceList = useCallback(async () => {
    try {
      const request_params = new URLSearchParams();
      request_params.set("devType", devType);
      request_params.set("groupId", groupId);
      request_params.set("action", "get_devs");

      const responseObject = await http_request(
        `${ac_cgi_url}?${request_params}`,
        null,
        "GET",
        {}
      );

      if (!responseObject.success) {
        messageApi.warning(responseObject.msg);
        return;
      }

      // 处理设备列表数据
      const deviceList = responseObject.data.map((device: any) => ({
        key: device.mac,
        ...device,
      }));

      setDeviceListData(deviceList);
    } catch (error) {
      console.error("获取设备列表失败:", error);
    }
  }, [devType, groupId, messageApi]);

  // 定时刷新设备列表，但不显示loading状态
  useInterval({
    callback: () => {
      fetchDeviceList();
    },
    delay: autoRefresh ? refreshInterval * 1000 : null,
    immediate: false, // 不立即执行，等开启自动刷新后才开始
  });

  // 设备操作函数
  const handleDeviceAction = (action: string, device: DeviceListItem) => {
    // 单个设备操作转为调用批量操作API
    set_actions(action, [device.mac]);
  };

  // 新增批量操作函数
  const set_actions = async (action: string, macList: string[]) => {
    if (!macList || macList.length === 0) {
      messageApi.warning("请选择需要操作的设备");
      return;
    }

    // 根据操作类型显示确认对话框
    let confirmTitle = "确认操作";
    let confirmContent = "";

    switch (action) {
      case "restart":
        confirmTitle = "确认重启";
        confirmContent = `您确定要重启选中的 ${macList.length} 台设备吗？`;
        break;
      case "reset":
        confirmTitle = "确认恢复出厂";
        confirmContent = `您确定要将选中的 ${macList.length} 台设备恢复出厂设置吗？此操作不可撤销！`;
        break;
      case "upgrade":
        confirmTitle = "确认升级";
        confirmContent = `您确定要升级选中的 ${macList.length} 台设备吗？`;
        break;
      case "unbind":
        confirmTitle = "确认解绑";
        confirmContent = `您确定要解绑选中的 ${macList.length} 台设备吗？`;
        break;
      default:
        break;
    }

    Modal.confirm({
      title: confirmTitle,
      content: confirmContent,
      onOk: async () => {
        setLoading(true);
        try {
          const values = {
            devType,
            dev_list: macList,
            action: "set_actions",
            dev_action: action,
            groupId: groupId, // 传递分组ID，用于分组操作
          };
          const responseObject = await http_request(
            ac_cgi_url,
            values,
            "POST",
            {}
          );

          if (!responseObject.success) {
            messageApi.warning(responseObject.msg || "操作失败");
          } else {
            messageApi.success(responseObject.msg || "操作成功");
            // 操作成功后清空选择并刷新表格
            setSelectedRowKeys([]);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        } catch (error) {
          console.error("设备操作失败:", error);
          messageApi.error("操作过程发生错误");
        } finally {
          setLoading(false);
        }
      },
    });
  };

  // 设备详情渲染函数 - 用于 ProTable 的 expandable
  const expandedRowRender = (record: DeviceListItem) => {
    return (
      <div style={{ padding: "16px" }}>
        <p>
          <strong>设备名称:</strong>{" "}
          {record.name || `设备_${record.mac.substring(record.mac.length - 5)}`}
        </p>
        <p>
          <strong>MAC地址:</strong> {record.mac}
        </p>
        <p>
          <strong>IP地址:</strong> {record.ipAddr || "未知"}
        </p>
        <p>
          <strong>型号:</strong> {record.model}
        </p>
        <p>
          <strong>版本:</strong> {record.version || "未知"}
        </p>
        <p>
          <strong>状态:</strong> {record.binded ? "已绑定" : "未绑定"}
        </p>
        <p>
          <strong>所属分组:</strong> {record.groupId}
        </p>
      </div>
    );
  };

  // 删除原有的列定义，使用从data.tsx导入的getColumns函数
  const columns = getColumns(setExpandedRowKeys, handleDeviceAction);

  return (
    <ProTable<DeviceListItem>
      size="small"
      actionRef={actionRef}
      columns={columns}
      dataSource={deviceListData}
      request={async (params) => {
        setLoading(true);
        await fetchDeviceList();
        setLoading(false);
        return {
          data: deviceListData,
          success: true,
          total: deviceListData.length,
        };
      }}
      loading={loading}
      rowKey="key"
      pagination={{
        pageSize: 10,
        showQuickJumper: true,
      }}
      expandable={{
        expandedRowRender,
        expandedRowKeys,
        onExpandedRowsChange: (keys) => setExpandedRowKeys(keys as string[]),
        rowExpandable: () => true,
      }}
      options={{
        density: true,
        setting: true,
      }}
      search={false}
      dateFormatter="string"
      headerTitle="设备列表"
      // 添加批量选择功能
      rowSelection={{
        selectedRowKeys,
        onChange: (keys) => setSelectedRowKeys(keys as string[]),
      }}
      toolBarRender={() => [
        <Space key="actions">
          {/* 批量操作按钮 */}
          <Space>
            <Button
              className="DangerButton"
              type="primary"
              style={buttonStyle}
              disabled={selectedRowKeys.length === 0}
              onClick={() => {
                set_actions("restart", selectedRowKeys);
              }}
              size="small"
            >
              批量重启
            </Button>
            <Button
              type="primary"
              className="DangerButton"
              style={buttonStyle}
              disabled={selectedRowKeys.length === 0}
              onClick={() => {
                set_actions("upgrade", selectedRowKeys);
              }}
              size="small"
            >
              批量升级
            </Button>
            {/* 修复：移除 disabled 属性，改为条件渲染或通过按钮状态控制 */}
            <TableDropdown
              key="batchActions"
              menus={[
                { key: "reset", name: "批量恢复出厂" },
                { key: "unbind", name: "批量解绑设备" },
              ]}
              onSelect={(key) => {
                // 在回调中判断是否有选中行
                if (selectedRowKeys.length > 0) {
                  set_actions(key, selectedRowKeys);
                } else {
                  messageApi.warning("请选择需要操作的设备");
                }
              }}
            >
              <Tooltip title="更多批量操作选项">
                <Button
                  type="primary"
                  style={buttonStyle}
                  size="small"
                  disabled={selectedRowKeys.length === 0}
                >
                  更多操作
                </Button>
              </Tooltip>
            </TableDropdown>
          </Space>

          {/* 自动刷新设置 */}
          <Space>
            <span>自动刷新:</span>
            <Switch
              checked={autoRefresh}
              onChange={(checked) => {
                setAutoRefresh(checked);
                if (checked) {
                  // 开启自动刷新时，立即执行一次刷新
                  fetchDeviceList();
                }
              }}
              size="small"
            />
            <Select
              value={refreshInterval}
              onChange={(value) => {
                setRefreshInterval(value);
              }}
              style={buttonStyle}
              popupMatchSelectWidth={false}
              size="small"
              variant="outlined"
              disabled={!autoRefresh}
              options={refreshOptions}
            />
          </Space>
        </Space>,
      ]}
    />
  );
};

export default DevListView;
